<?php
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/10/13
 * Time: 12:21
 */

class Wenjuan_model extends Base_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function getWenjuanQuestion($wenjuanid)
    {
        $wenjuan=$this->db->select('w.wenjuangroupid as gid,g.align as align')->from('wenjuan as w')
            ->join('wenjuan_group as g','w.wenjuangroupid=g.id')
            ->where('w.id',$wenjuanid)
            ->get()->row_array();
        $qdata=$this->db->select('*')->from('wenjuan_question')
            ->where('wenjuangroupid',$wenjuan['gid'])
            ->order_by('sort','ASC')
            ->get()->result_array();
        foreach ($qdata as &$q){
            $itemdata = $this->db->select('*')->from('wenjuan_item')
                ->where('qid =',$q['id'])
                ->order_by('sort','ASC')
                ->get()->result_array();
            $q['itemdata'] = $itemdata;
        }
        return array('qdata'=>$qdata,'align'=>$wenjuan['align']);
    }

    public function checkUserComplish($wenjuanid,$uid)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $iscomplished=$redis->getBit('wenjuan.'.$wenjuanid.'.complished',$uid);
        //获取问卷背景和前言
        $wdata = $wenjuan=$this->db->select('w.wenjuangroupid as gid,g.restype as restype,g.clientrestype,
        g.bgurl as bg,g.introduction as intro,g.shareimg as img,g.sharetitle as title,g.sharedesc as desc')
            ->from('wenjuan as w')
            ->join('wenjuan_group as g','w.wenjuangroupid=g.id')
            ->where('w.id',$wenjuanid)
            ->get()->row_array();
        $restype = (int)$wdata['restype'];
        $clientrestype = (int)$wdata['clientrestype'];
        $gid = (int)$wdata['gid'];
        $intro = $wdata['intro'];
        $bgurl = "http://wap.nldou.com".$wdata['bg'];
        $img = "http://wap.nldou.com".$wdata['img'];
        $title = $wdata['title'];
        $desc = $wdata['desc'];

        if ($iscomplished===1){
            $resdata = $this->getResults($restype,$gid,$wenjuanid,$uid,$redis);
            return array("status"=>2,"uid"=>$uid,"restype"=>$clientrestype,"ansdata"=>$resdata,
                "sharetitle"=>$title,"shareimg"=>$img,"sharedesc"=>$desc,
                "intro"=>$intro,"bgurl"=>$bgurl);
        }else{
            //查询问卷截止日期
            $stop=$this->db->select('stop')->from('wenjuan')->where('id =',$wenjuanid)->get()->row_array();
            $stop=(int)$stop['stop']+24*3600;
            //超过截止日期，问卷失效
            if (time()>$stop) {return array("status"=>3);}
            else{return array("status"=>1,"uid"=>$uid,
                "sharetitle"=>$title,"shareimg"=>$img,"sharedesc"=>$desc,
                "intro"=>$intro,"bgurl"=>$bgurl);}
        }
    }

    public function submitName($uid,$name,$wenjuanid)
    {
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $redis->set('wenjuan.username.'.$wenjuanid.'.'.$uid,$name);
    }

    public function submitAns($uid,$wenjuanid,$ans)
    {
        $wjdata = $this->db->select('g.type as type,g.restype as restype,g.clientrestype,g.id as gid')->from('wenjuan as w')->join('wenjuan_group as g','g.id=w.wenjuangroupid','left')->where('w.id',$wenjuanid)->get()->row_array();
        $wjtype = (int)$wjdata['type'];
        $gid = $wjdata['gid'];
        $restype = (int)$wjdata['restype'];
        $clientrestype = (int)$wjdata['clientrestype'];

        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $redis->setBit('wenjuan.'.$wenjuanid.'.complished',$uid,1);
        $redis->sAdd('wenjuan.'.$wenjuanid.'.complished.uid',$uid);
        //不允许重新答题，如果重新答题，需将下方的数据删除
        if ($wjtype === 1){
            //聚合统计，所有问题的选项一样
            foreach ($ans as $an){
                //用户的选项
                $redis->sAdd('wenjuan.'.$wenjuanid.'.u'.$uid.'.'.$an['key'],$an['qid']);
                //选择该选项的用户
                $redis->sAdd('wenjuan.'.$wenjuanid.'.q'.$an['qid'].'.'.$an['key'],$uid);
            }
        }elseif ($wjtype === 2){
            //分题目统计，每个问题的选项都不相同
            foreach ($ans as $an){
                //用户每题的选项
                $redis->set('wenjuan.'.$wenjuanid.'u'.$uid.'.q'.$an['qid'],$an['key']);
                //选择该选项的用户
                $redis->sAdd('wenjuan.'.$wenjuanid.'.q'.$an['qid'].'.'.$an['key'],$uid);
            }
        }
        $data = $this->getResults($restype,$gid,$wenjuanid,$uid,$redis);
        return array('restype'=>$clientrestype,'ansdata'=>$data);
    }

    public function getResults($restype,$gid,$wenjuanid,$uid,$redis)
    {
        $data = array();
        if ($restype === 1){
            //聚合统计,所有问题的选项一样
            $example = $this->db->select('id')->from('wenjuan_question')->where('wenjuangroupid ='.$gid)
                ->limit(1,0)->get()->row_array();
            $items = $this->db->select('key,content,color')->from('wenjuan_item')->where('qid',$example['id'])->order_by('sort','ASC')->get()->result_array();
            foreach ($items as $item){
                $qids=$redis->sMembers('wenjuan.'.$wenjuanid.'.u'.$uid.'.'.$item['key']);
                $ans=array();
                if (!empty($qids)){
                    $qsorts=$this->db->select('sort')->from('wenjuan_question')->where_in('id',$qids)->order_by('sort','ASC')->get()->result_array();
                    foreach ($qsorts as $qsort){
                        $ans[]=$qsort['sort'];
                    }
                }
                $ansnum=count($ans);
                $data['data'][] = array('content'=>$item['content'],'num'=>$ansnum,'ans'=>$ans,'color'=>$item['color']);
            }
        }elseif ($restype === 2){
            //青少年课程测试
            $data =$this->getUpChildResults($gid,$redis,$wenjuanid,$uid);
        }elseif ($restype === 3){
            //优势累积测测你有多焦虑
            $data = $this->getWorriesResults($gid,$redis,$wenjuanid,$uid);
        }elseif ($restype === 4) {
            //优势累积你的幸福是怎么样的
            $data = $this->getHappinessResults($gid,$redis,$wenjuanid,$uid);
        }elseif ($restype === 5) {
            //沟通方式是怎么样的
            $data = $this->getConnectResults($gid,$redis,$wenjuanid,$uid);
        }
        return $data;
    }

    public function getConnectResults($gid,$redis,$wenjuanid,$uid)
    {
        $qids = $this->db->select('id')->from('wenjuan_question')->where('wenjuangroupid ='.$gid)
            ->order_by('sort','ASC')
            ->get()->result_array();
        $items = $this->db->select('key,content,color')->from('wenjuan_item')->where('qid',$qids[0]['id'])->order_by('sort','ASC')->get()->result_array();
        //读取答案
        $redis->multi();
        foreach ($qids as $qid){
            $redis->get('wenjuan.'.$wenjuanid.'u'.$uid.'.q'.$qid['id']);
        }
        $ansres = $redis->exec();
        $ans = array();
        foreach ($ansres as $i => $a){
            $ans[$a][] = $i + 1;
        }
        //组合数据
        $data = array();
        foreach ($items as $item){
            $itemans = isset($ans[$item['key']]) ? $ans[$item['key']] : array();
            $ansnum = count($itemans);
            $data[] = array('content'=>$item['content'],'num'=>$ansnum,'ans'=>$itemans,'color'=>$item['color']);
        }
        //说明内容
        $intro = array(
            'hcell'=>'说明',
            'bcells'=>array(
                '一般来说，人际行为有三种广泛类型，即：被动型，侵略型，自信型',
                '0',
                '测试中，“a”选项代表了被动型，“b”选项代表了侵略型，“c”选项代表了自信型',
                '因此，你选择的对应选项越多，你就越倾向于其对应的类型。如果你选了≥6个的某个选项，表明你在人际交往中很可能就是其对应的类型',
                '0',
                '被动型人际交往行为的特征是不作为。这类人往往很容易相处，较为乐观，但他们害怕冒犯他人，所以往往不愿为自己的权利挺身而出。他们表达愤怒时很不自在，出现这种感觉时通常会否认或抑制。因此，很容易在压力和紧张之下滋生怨恨。这种类型的人最后会变得害怕亲密关系，因为他们无力应对大多数关系中都会出现琐碎烦恼和无意侵扰',
                '0',
                '侵略型人际交往行为的特点是咄咄逼人。这类人倾向于追求他们想要的但并不关心这对其他人的影响。他们愤怒、霸道的态度往往会疏远那些最终可能会反对他们的人。攻击性强的人通常对他人持怀疑态度，他们往往留心他人的违规行为或对自身权利的侵犯。因此，侵略型人际交往行为会产生压力，阻碍亲密、互相信任、互相关心的人际关系的发展',
                '0',
                '自信型人际交往行为的特点是公正和力量兼备。自信的人能够捍卫自己的权利，同时对他人的权利保持敏感。选择这种行事风格的人通常都很放松，也很容易相处，同时，他们对自己的感觉很诚实。这是减少压力和维持长期亲密关系的最佳方式',
            )
        );

        return array('data'=>$data, 'introdata'=>$intro);
    }

    public function getUpChildResults($gid,$redis,$wenjuanid,$uid,$ans=array())
    {
        //获取用户答案
        if (empty($ans)){
            $qids = $this->db->select('id')->from('wenjuan_question')->where('wenjuangroupid ='.$gid)
                ->order_by('sort','ASC')
                ->get()->result_array();
            //读取答案
            $redis->multi();
            foreach ($qids as $qid){
                $redis->get('wenjuan.'.$wenjuanid.'u'.$uid.'.q'.$qid['id']);
            }
            $ansres = $redis->exec();
            $ans = array();
            foreach ($ansres as $a){
                $ansrow = array();
                $ansrow['key']=$a;
                $ans[] = $ansrow;
            }
        }

        $pmb = array(12,17,23,27,30,32,34,35);
        $pmbcnt = 0;
        $pmg = array(4,8,22,38,39,40,41,42);
        $pmgcnt = 0;

        $pvb = array(11,14,19,20,26,45,46,47);
        $pvbcnt = 0;
        $pvg = array(0,2,16,24,29,31,33,36);
        $pvgcnt = 0;

        $psb = array(5,6,9,10,13,25,28,37);
        $psbcnt = 0;
        $psg = array(1,3,7,15,18,21,43,44);
        $psgcnt = 0;

        $pointarr = array(
            array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),/*1-5*/
            array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),/*6-10*/
            array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),/*11-15*/
            array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),/*16-20*/
            array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),/*21-25*/
            array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),/*26-30*/
            array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),/*31-35*/
            array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),/*36-40*/
            array('a'=>0,'b'=>1),array('a'=>0,'b'=>1),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>0,'b'=>1),/*41-45*/
            array('a'=>1,'b'=>0),array('a'=>1,'b'=>0),array('a'=>1,'b'=>0)/*46-48*/
        );
        foreach ($pmb as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $pmbcnt+=$p;
        }
        foreach ($pmg as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $pmgcnt+=$p;
        }
        foreach ($pvb as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $pvbcnt+=$p;
        }
        foreach ($pvg as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $pvgcnt+=$p;
        }
        foreach ($psb as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $psbcnt+=$p;
        }
        foreach ($psg as $sort){
            $key = $ans[$sort]['key'];
            $p = $pointarr[$sort][$key];
            $psgcnt+=$p;
        }

        $hobcnt = $pmbcnt+$pvbcnt;
        $bcnt = $pmbcnt+$pvbcnt+$psgcnt;
        $gcnt = $pmgcnt+$pvgcnt+$psgcnt;
        $diffGB= $gcnt-$bcnt;
        $header = array('计分项目','得分');
        $body = array(
            array('rowheader'=>'PMB','rowcells'=>array($pmbcnt)),
            array('rowheader'=>'PMG','rowcells'=>array($pmgcnt)),
            array('rowheader'=>'PVB','rowcells'=>array($pvbcnt)),
            array('rowheader'=>'PVG','rowcells'=>array($pvgcnt)),
            array('rowheader'=>'HOB','rowcells'=>array($hobcnt)),
            array('rowheader'=>'PSB','rowcells'=>array($psbcnt)),
            array('rowheader'=>'PSG','rowcells'=>array($psgcnt)),
            array('rowheader'=>'B类总分','rowcells'=>array($bcnt)),
            array('rowheader'=>'G类总分','rowcells'=>array($gcnt)),
            array('rowheader'=>'G-B','rowcells'=>array($diffGB))
        );
        $data = array('hcells'=>$header,'bcells'=>$body);
        return $data;
    }

    public function getWorriesResults($gid,$redis,$wenjuanid,$uid,$items=array())
    {
        //获取问题选项
        if (empty($items)){
            $example = $this->db->select('id')->from('wenjuan_question')->where('wenjuangroupid ='.$gid)
                ->limit(1,0)->get()->row_array();
            $items = $this->db->select('key')->from('wenjuan_item')->where('qid',$example['id'])->order_by('sort','ASC')->get()->result_array();
        }

        $scorearr = array(
            'a'=>array('104'=>4,'105'=>4,'106'=>1,'107'=>1,'108'=>1,'109'=>1,'110'=>4,'111'=>4,'112'=>1,'113'=>1),
            'b'=>array('104'=>3,'105'=>3,'106'=>2,'107'=>2,'108'=>2,'109'=>2,'110'=>3,'111'=>3,'112'=>2,'113'=>2),
            'c'=>array('104'=>2,'105'=>2,'106'=>3,'107'=>3,'108'=>3,'109'=>3,'110'=>2,'111'=>2,'112'=>3,'113'=>3),
            'd'=>array('104'=>1,'105'=>1,'106'=>4,'107'=>4,'108'=>4,'109'=>4,'110'=>1,'111'=>1,'112'=>4,'113'=>4)
        );
        $score = 0;
        foreach ($items as $item){
            $qids=$redis->sMembers('wenjuan.'.$wenjuanid.'.u'.$uid.'.'.$item['key']);
            foreach($qids as $qid){
                $score += $scorearr[$item['key']][$qid];
            }
        }
        $body = array(
            array('rowheader'=>'评测分数','hw'=>'25%','cw'=>'75%','rowcells'=>array($score))
        );

        $intro = array(
            'hcell'=>'说明',
            'bcells'=>array(
                '10-11分，焦虑程度很低',
                '13-14分，焦虑程度比较低',
                '16-17分，焦虑程度一般',
                '19-20分，焦虑程度比较高',
                '22-24分，如果你是男性,说明你的焦虑程度很高',
                '24-26分，如果你是女性,说明你的焦虑程度很高',
                '注意：成年男性和女性的平均分略有不同,女性的焦虑程度要略高于男性'
            )
        );

        return array('bcells'=>$body,'introdata'=>$intro);
    }

    public function getHappinessResults($gid,$redis,$wenjuanid,$uid,$items=array())
    {
        //获取问题选项
        if (empty($items)){
            $example = $this->db->select('id')->from('wenjuan_question')->where('wenjuangroupid ='.$gid)
                ->limit(1,0)->get()->row_array();
            $items = $this->db->select('key')->from('wenjuan_item')->where('qid',$example['id'])->order_by('sort','ASC')->get()->result_array();
        }

        $qtypearr = array(
            //快乐取向
            '116'=>'happy','125'=>'happy','127'=>'happy','129'=>'happy',
            '132'=>'happy','141'=>'happy','144'=>'happy','145'=>'happy',
            '158'=>'happy','167'=>'happy','170'=>'happy','171'=>'happy',
            //投入取向
            '117'=>'input','119'=>'input','120'=>'input','121'=>'input',
            '133'=>'input','135'=>'input','136'=>'input','137'=>'input',
            '159'=>'input','161'=>'input','162'=>'input','163'=>'input',
            //意义取向
            '114'=>'meanning','122'=>'meanning','123'=>'meanning','126'=>'meanning',
            '131'=>'meanning','138'=>'meanning','139'=>'meanning','142'=>'meanning',
            '157'=>'meanning','164'=>'meanning','165'=>'meanning','168'=>'meanning',
            //胜利取向
            '118'=>'victory','124'=>'victory','128'=>'victory','130'=>'victory',
            '134'=>'victory','140'=>'victory','143'=>'victory','146'=>'victory',
            '160'=>'victory','166'=>'victory','169'=>'victory','172'=>'victory',
        );

        $scorearr = array('a'=>5,'b'=>4, 'c'=>3, 'd'=>2, 'e'=>1);
        $results = array('happy'=>0,'input'=>0,'meanning'=>0,'victory'=>0);

        foreach ($items as $item){
            $qids=$redis->sMembers('wenjuan.'.$wenjuanid.'.u'.$uid.'.'.$item['key']);
            foreach($qids as $qid){
                $qtype = $qtypearr[(string)$qid];
                $score = $scorearr[$item['key']];
                $results[$qtype] += $score;
            }
        }

        $header = array('测试项目','得分');
        $body = array(
            array('rowheader'=>'快乐取向','hw'=>'50%','cw'=>'50%','rowcells'=>array($results['happy'])),
            array('rowheader'=>'投入去向','hw'=>'50%','cw'=>'50%','rowcells'=>array($results['input'])),
            array('rowheader'=>'意义取向','hw'=>'50%','cw'=>'50%','rowcells'=>array($results['meanning'])),
            array('rowheader'=>'胜利取向','hw'=>'50%','cw'=>'50%','rowcells'=>array($results['victory']))
        );
        $intro = array(
            'hcell'=>'说明',
            'bcells'=>array(
                '1. 四项总分当中得分最高的就是你的幸福的主导取向',
                '2. 如果四个取向均高于15分，说明你可能追求的是一种完整的生活,而且极有可能对生活高度地满意',
                '3. 如果四个取向均低于9分，这说明你的生活比较空虚, 很有可能对生活感到不满'
            )
        );

        $data = array('hcells'=>$header,'bcells'=>$body,'introdata'=>$intro);
        return $data;
    }

    public function getStatis($wenjuanid)
    {
        $wenjuan=$this->db->select('wenjuangroupid')->from('wenjuan')->where('id =',$wenjuanid)->get()->row_array();
        $ques=$this->db->select('*')->from('wenjuan_question')->where('wenjuangroupid=',$wenjuan['wenjuangroupid'])->order_by('sort','ASC')->get()->result_array();
        $this->load->model('redis_model');
        $redis=$this->redis_model->getRedisInstance();
        $items = $this->db->from('wenjuan_item')->where('qid ='.$ques[0]['id'])
            ->order_by('sort','ASC')->get()->result_array();

        $data=array();
        foreach ($ques as $q) {
            $numarr = array();
            $totalnum = 0;
            foreach ($items as $item){
                $numrow=array();
                $itemnum=$redis->sCard('wenjuan.'.$wenjuanid.'.q'.$q['id'].'.'.$item['key']);
                $numrow['num']=(int)$itemnum;
                $numrow['item']=$item['item'];
                $numrow['color']=$item['color'];
                $numarr[]=$numrow;
                $totalnum+=$numrow['num'];
            }
            foreach ($numarr as &$n){
                $itemper=$totalnum==0?"0":round($n['num']/$totalnum,3)*100;
                $itemper=$itemper.'%';
                $n['per']=$itemper;
            }
            $data[]=array("sort"=>$q['sort'],"question"=>$q['question'],"numarr"=>$numarr);
        }
        return $data;
    }

}